package com.jauto.auto.utils;

import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 〈功能概述〉<br>
 *
 * @className: ImgUtils
 * @package: com.jauto.auto.utils
 * @author: zhangRenHuo
 * @date: 2020/10/15 16:27
 */
public class ImgUtils {

    /**
     * 将图片转换成Base64编码的字符串
     *
     * @param path
     * @return base64编码的字符串
     */
    public static String imageToBase64(String path) {
        InputStream inputStream = null;
        byte[] data = null;
        String result = null;
        try {
            inputStream = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[inputStream.available()];
            //写入数组
            inputStream.read(data);
            //用默认的编码格式进行编码
            //对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            result = encoder.encode(data);
            result = "data:image/jpeg;base64,"+result.replaceAll("\n", "").replaceAll("\r", "");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }
}
